<script setup lang="ts">
import {
  type ColProps,
  TableColumn,
  TableRowSelection,
} from "@arco-design/web-vue";
import { onMounted, reactive, ref, h } from "vue";
import { tableBorder } from "@/utils/border/table-border.ts";
import {
  getAchievementList,
  getDetail, groupList,
  uploadData,
} from "@/services/achievement";
import type { achievementType } from "@/types/achievement";
import type {
  ListRacetrackType,
  OtherChildrenListType,
} from "@/types/commonType.ts";
import {
  getDictByParentCode,
  listNormalRacetrack,
  listRacetrack,
} from "@/services/commonApi.ts";
import { getUser, downloadFile } from "@/utils";
import AchieveModal from "@/pages/review/achievement/AchieveModal.vue";
import {standardList} from "@/services/scoreApi.ts";
import type {GroupListType} from "@/types/expertGroup.ts";

const colProps: ColProps = {
  xs: 24,
  sm: 24,
  md: 12,
  lg: 6,
  xl: 6,
  xxl: 6,
  span: 6,
};

const achieveRef = ref<{
  init: (data: achievementType) => void;
}>();

const data = ref<[]>([]);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
});

const loading = reactive({
  search: false, // 查询
  reset: false, // 重置
  table: false, // 表格
  decrypt: false, // 解密
  print: false, // 打印
  export: false, // 导出
});

const searchValue = reactive({
  phone: "",
  projectType: "",
  channel: "",
  projectSource: "",
  groupId: ""
});

const visible = ref(false);
const drawer = ref<{
  showDialog: () => {};
  hideDialog: () => {};
}>();

const options = reactive<{
  参赛项目来源: OtherChildrenListType[];
  赛道: ListRacetrackType[];
  企业赛道: ListRacetrackType[];
  loading: boolean;
  export: boolean;
  groupList: GroupListType[]
}>({
  参赛项目来源: [],
  赛道: [],
  企业赛道: [],
  loading: false,
  export: false,
  groupList: []
});
// 列表
const getList = () => {
  getAchievementList({
    current: pagination.current,
    size: pagination.pageSize,
    phone: searchValue.phone,
    projectType: searchValue.projectType,
    channel: searchValue.channel,
    projectSource: searchValue.projectSource,
    groupId: searchValue.groupId
  }).then((res) => {
    if (res.code === 200) {
      data.value = res.data.records;
      pagination.total = res.data.total;
      pagination.current = res.data.current;
      pagination.pageSize = res.data.size;
    }
  });
};
// 查询
const handleSearch = () => {
  pagination.current = 1;
  getList();
};

// 重置
const handleReset = () => {
  searchValue.phone = "";
  searchValue.projectType = "";
  searchValue.channel = "";
  searchValue.projectSource = "";
  searchValue.groupId = ""
  options["赛道"] = [];
  handleSearch();
};

// 分页
const handlePageChange = (page: number) => {
  pagination.current = page;
  getList();
};

// 导出
const handleExport = () => {
  uploadData(searchValue).then((res: any) => {
    downloadFile(res, `成绩统计.xlsx`);
  });
};

const columns = [
  {
    title: "电话",
    key: "phone",
    dataIndex: "phone",
    align: "center",
  },
  {
    title: "项目名称",
    key: "projectName",
    dataIndex: "projectName",
    align: "left",
  },
  {
    title: "赛道类型",
    key: "projectType",
    dataIndex: "projectType",
    align: "center",
    slotName: "projectType",
  },
  {
    title: "赛道",
    key: "channel",
    dataIndex: "channel",
    align: "center",
  },
  {
    title: "参赛项目来源",
    key: "projectSource",
    dataIndex: "projectSource",
    align: "center",
  },
  {
    title: "最高分",
    key: "maxScore",
    dataIndex: "maxScore",
    align: "center",
  },
  {
    title: "最低分",
    key: "minScore",
    dataIndex: "minScore",
    align: "center",
  },
  {
    title: "平均分",
    key: "finalScore",
    dataIndex: "finalScore",
    align: "center",
  },
  {
    title: "操作",
    slotName: "operate",
    align: "center",
    width: 160,
    fixed: "right",
  },
];

const getColor = (projectType: string) => {
  switch (projectType) {
    case "1":
      return "#168cff";
    case "0":
      return "#00b42a";
  }
};

const getName = (projectType: string) => {
  switch (projectType) {
    case "1":
      return "企业";
    case "0":
      return "常规";
  }
};



const optionsList = () => {
  getDictByParentCode({
    dictCode: "参赛项目来源",
  }).then((res) => {
    if (res.code === 200) {
      options["参赛项目来源"] = res.data[0].children;
      // itemText
      const find = options["参赛项目来源"].find(
        (item) => item.itemText === getUser().username
      );
      if (find) {
        searchValue.projectSource = find.id;
        options["参赛项目来源"] = [find];
      } else {
        searchValue.projectSource = "";
      }
    }
  });
};
const handleSelectChange = (e) => {
  searchValue.channel = "";
  options["赛道"] = [];
  if (e === "0") {
    listNormalRacetrack().then((res) => {
      if (res.code === 200) {
        options["赛道"] = res.data;
      }
    });
  } else {
    listRacetrack().then((res) => {
      if (res.code === 200) {
        options["赛道"] = res.data;
      }
    });
  }
};
const form = reactive({
  records: [],
  teachers: [],
});

const handleDetail = (row: achievementType) => {
  form.records = [];
  form.teachers = [];
  standardList({moduleId: row.moduleId}).then(module => {
    if (module.code === 200) {
      const data = module.data
      getDetail({
        registUid: row.registUid,
      }).then((res) => {
        console.log(res)
        if (res.code === 200) {
          res.data.forEach((item) => {
            // console.log(item)
            const l = item.recordList
            const list = module.data.map(key => {
              // console.log(key)
              const find = l.find(f => f.standardId === key.id)
              return {
                ...key,
                score: find ? find.score : 0,
                markTime: find ? find.markTime : 0,
              }
            })
            console.log(list)
            // console.log(item.recordList)
            form.records.push(list);
            form.teachers.push({
              teacherName: item.teacherName,
              teacherId: item.teacherId,
            });
          });
        }
      });
    }
  })


  visible.value = true;
};

const handleAchieve = (row: achievementType) => {
  achieveRef.value?.init(row);
};

onMounted(() => {
  optionsList();
  groupList().then(res => {
    if (res.code === 200) {
      options.groupList = res.data
    }
  }).finally(getList)
});


const handleCancel = () => {
  // drawer.value?.hideDialog();
  // console.log(drawer.value)
};

const handleClose = () => {
  visible.value = false;
};

function formatLevel1TextWithBoldIntro(text: string) {
  // 判断是否以编号开头（如 1.、2.）
  // const startsWithNumber = /^\d+\./.test(text);

  if (text) {
    const startsWithNumber = /^[1-9]\d*\./.test(text);

    if (startsWithNumber) {
      // 如果以编号开头，只换行，不加粗
      return text.replace(/(\d+\..*?)(?=\d+\.|$)/gs, "<br>$1").trim();
    }

    // 否则，加粗开头部分，换行编号部分
    const regex = /^([^\d]+?)(?=\d+\.)/s;
    console.log(text)
    const match = text.match(regex);
    console.log(match)

    if (match) {
      const [, intro] = match;
      const numberedContent = text.substring(intro.length).trim();
      const formattedNumberedContent = numberedContent.replace(
          /(\d+\..*?)(?=\d+\.|$)/gs,
          "<br>$1"
      );
      return `<strong style="font-size: 15px;">${intro.trim()}</strong>${formattedNumberedContent}`;
    }

    if (text.includes("0.5分")) {
      console.log(111);
      return text;
    }

    // 如果没有编号，只加粗并换行
    return `<strong>${text}</strong><br>`;
  }
  return ""
}

const columnsForm: TableColumn[] = [
  {
    title: "序号",
    dataIndex: "index",
    width: 80,
    slotName: "index",
    align: "center",
  },
  {
    title: "一级指标",
    key: "name",
    dataIndex: "name",
    align: "center",
    width: 150,
  },
  {
    title: "分值",
    key: "level1",
    dataIndex: "level1",
    align: "center",
    width: 100,
  },
  {
    title: "指标描述",
    dataIndex: "level2",
    render: ({ record }) => {
      console.log(record)
      return h("div", {
        innerHTML: formatLevel1TextWithBoldIntro(record.level2),
      });
    },
  },
  {
    title: "分数",
    key: "score",
    dataIndex: "score",
    align: "center",
    width: 80,
  },
  {
    title: "评分时间",
    key: "markTime",
    dataIndex: "markTime",
    align: "center",
    width: 200,
  },
];

const spanMethodAll = ({ column, rowIndex, record }) => {
  // 指标描述
  // 遍历form.records数组
  // console.log(form.records)/
  for (const item of form.records) {
    if (item.length) {
      if (column.dataIndex === "name") {
        const prevRecord = rowIndex > 0 ? item[rowIndex - 1].name : null;
        if (prevRecord && prevRecord === record.name) {
          return { rowspan: 0, colspan: 0 }; // 不显示当前单元格
        } else {
          const sameNameCount = item.filter(
            (i) => i.name === record.name
          ).length;
          return { rowspan: sameNameCount, colspan: 1 }; // 合并单元格
        }
      }
      if (column.dataIndex === "score") {
        const prevRecord = rowIndex > 0 ? item[rowIndex - 1].name : null;
        if (prevRecord && prevRecord === record.name) {
          return { rowspan: 0, colspan: 0 }; // 不显示当前单元格
        } else {
          const sameNameCount = item.filter(
              (i) => i.name === record.name
          ).length;
          return { rowspan: sameNameCount, colspan: 1 }; // 合并单元格
        }
      }
      if (column.dataIndex === "markTime") {
        const prevRecord = rowIndex > 0 ? item[rowIndex - 1].name : null;
        if (prevRecord && prevRecord === record.name) {
          return { rowspan: 0, colspan: 0 }; // 不显示当前单元格
        } else {
          const sameNameCount = item.filter(
              (i) => i.name === record.name
          ).length;
          return { rowspan: sameNameCount, colspan: 1 }; // 合并单元格
        }
      }
      return { rowspan: 1, colspan: 1 };
    }
  }
};

const computedTotalScore = (record: any[]) => {
  return record.reduce((sum, item) => sum + (item.score || 0), 0);
};
</script>

<template>
  <a-space
    class="container"
    direction="vertical"
  >
    <a-card>
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col v-bind="colProps">
            <a-form-item label="报名用户手机号">
              <a-input
                allow-clear
                v-model="searchValue.phone"
                placeholder="请输入报名用户手机号"
              />
            </a-form-item>
          </a-col>

          <a-col v-bind="colProps">
            <a-form-item label="赛道类型">
              <a-select
                v-model="searchValue.projectType"
                @change="handleSelectChange"
                placeholder="请选择赛题类型"
              >
                <a-option value="0">常规赛题</a-option>
                <a-option value="1">企业需求子赛题</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col v-bind="colProps">
            <a-form-item label="赛道">
              <a-select
                v-model="searchValue.channel"
                placeholder="请选择赛道"
              >
                <a-option
                  v-for="item in options['赛道']"
                  :key="item.id"
                  :value="item.id"
                >{{ item.dictName }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col v-bind="colProps">
            <a-form-item label="参赛项目来源">
              <a-select
                v-model="searchValue.projectSource"
                placeholder="请选择参赛项目来源"
              >
                <a-option
                  v-for="item in options['参赛项目来源']"
                  :key="item.id"
                  :value="item.id"
                >{{ item.itemText }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col v-bind="colProps">
            <a-form-item label="专家组">
              <a-select
                  v-model="searchValue.groupId"
                  placeholder="请选择专家组"
                  allow-search
              >
                <a-option
                    v-for="item in options.groupList"
                    :key="item.id"
                    :value="item.id"
                >{{ item.name }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col v-bind="colProps">
            <a-form-item>
              <a-space>
                <a-button
                  type="primary"
                  @click="handleSearch"
                  :loading="loading.search"
                >
                  <template #icon>
                    <icon-search />
                  </template>
                  <span>查询</span>
                </a-button>
                <a-button
                  @click="handleReset"
                  :loading="loading.reset"
                >
                  <template #icon>
                    <icon-refresh />
                  </template>
                  <span>重置</span>
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <div class="tabletools">
        <a-space>
          <a-button
            type="outline"
            :loading="loading.export"
            @click="handleExport"
          >导出</a-button>
        </a-space>
      </div>
      <a-table
        :loading="loading.table"
        :data="data"
        :columns="columns"
        :bordered="tableBorder"
        :pagination="pagination"
        @page-change="handlePageChange"
      >
        <template #projectType="{record}">
          <a-tag :color="getColor(record.projectType)">{{ getName(record.projectType) }}</a-tag>
        </template>

        <template #operate="{ record }">
          <a-space>
            <a-button
              type="primary"
              @click="handleDetail(record)"
            >详情</a-button>
            <a-button
              type="primary"
              @click="handleAchieve(record)"
            >项目详细</a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </a-space>

  <a-modal
    width="80%"
    :closable="false"
    @cancel="handleCancel"
    v-model:visible="visible"
    ref="drawer"
    title="成绩详情"
  >
    <div style="height: 500px;overflow:auto;">
      <div
        v-for="(record, index) in form.records"
        :key="index"
      >
        <h3>{{ form.teachers[index].teacherName }}，总分：{{ computedTotalScore(record) }}</h3>
        <a-table
          :data="record"
          :columns="columnsForm"
          :pagination="false"
          :bordered="tableBorder"
          :span-method="spanMethodAll"
        >
          <template #index="{rowIndex}">
            {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
          </template>
        </a-table>
      </div>
    </div>
    <template #footer>
      <a-button @click="handleClose">
        关闭
      </a-button>
    </template>
  </a-modal>
  <AchieveModal ref="achieveRef"></AchieveModal>
</template>

<style scoped lang="scss">
</style>
